package sessionbeans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.avalon.framework.service.ServiceManager;

import services.ClienteJMSBean;
import services.ServicesAdministrator;


import dto.ArticuloDTO;
import entitybeans.Articulo;
import entitybeans.CentroDistribucion;

@Stateless
public class ArticulosSessionBean implements Articulos {
	
	@PersistenceContext 
    private EntityManager em;
	@EJB
	private ServicesAdministrator sa;
	@Override
	public List<Articulo> getArticulos() {
		Query query = em.createQuery("SELECT a FROM Articulo a");
		return (List<Articulo>)query.getResultList();
	}
	public List<CentroDistribucion> getCentros() {
		Query query = em.createQuery("SELECT cd FROM CentroDistribucion cd");
		return (List<CentroDistribucion>)query.getResultList();
	}
	public boolean nuevoArticulo(ArticuloDTO replica){
		// TODO Auto-generated method stub
		Articulo art= replica.getEntityBean();
		Query query = em.createQuery("SELECT cd FROM CentroDistribucion cd");
		List<CentroDistribucion> centros = getCentros();
		try{
			em.persist(art);
//			art.getGeneratedXmlpath();
			sa.enviarNuevoArt(art, centros);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public ArticuloDTO getArticulo(Integer articulo_ref){
		Query q = em.createQuery("SELECT a FROM Articulo a WHERE a.ref=?").setParameter(1, articulo_ref);
		Articulo art = (Articulo)q.getSingleResult();
		ArticuloDTO replica= art.getDTO();
		return replica;
	}
}
